# What is plot.ly? A package to create interactive graphics. It uses the htmlwidget framework, and is compatible with lots of different programs. Very useful for online graphs etc. b/c your data points are easily identified.

# install.packages("plotly")

library(plotly)
## Loading required package: ggplot2
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
plot_ly(z = ~volcano) #just to see if it's installed properly
## No trace type specified:
##   Based on info supplied, a 'heatmap' trace seems appropriate.
##   Read more about this trace type -> https://plot.ly/r/reference/#heatmap
d <- mpg

#Two main ways to get a plotly object.

#plot_ly() transforms data into the object.
  #data frames not required, but highly recommended
  #basic structure: plot_ly( x , y ,type,mode,color ,size ) (type=type of graph(histogram etc., mode=format of data: points, lines, etc.)
  #layout(plot ,title , xaxis = list(title ,titlefont ), yaxis = list(title ,titlefont ))


p0 <- plot_ly(data=d, x= ~displ, y= ~cty)
p0
## No trace type specified:
##   Based on info supplied, a 'scatter' trace seems appropriate.
##   Read more about this trace type -> https://plot.ly/r/reference/#scatter
## No scatter mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plot.ly/r/reference/#scatter-mode
      #you NEED the ~, otherwise it doesn't work

#ggplotly() turns ggplot object into plotly object.
#Here's our original first ggplot. 
p1 <- ggplot(data=d,
             mapping = aes(x=displ, y=cty)) + geom_point()
p1

#Now, if we use plotly:
ggplotly(p1) #can mouse over and see what exactly each point is, can do for most ggplot2 functions.
p2 <- ggplot(d, aes(x=fl, y=hwy, group=fl))
p2 + geom_boxplot(fill="red")

myColors <- c("red", "darkgreen", "green", "blue", "orange")
ggplotly(p2 + geom_boxplot(fill=myColors))
#notice plotly vs ggplotly


# Can add "layers" with plotly:

head(txhousing) # this is real estate data from Texas
## # A tibble: 6 x 9
##   city     year month sales   volume median listings inventory  date
##   <chr>   <int> <int> <dbl>    <dbl>  <dbl>    <dbl>     <dbl> <dbl>
## 1 Abilene  2000     1    72  5380000  71400      701       6.3 2000 
## 2 Abilene  2000     2    98  6505000  58700      746       6.6 2000.
## 3 Abilene  2000     3   130  9285000  58100      784       6.8 2000.
## 4 Abilene  2000     4    98  9730000  68600      785       6.9 2000.
## 5 Abilene  2000     5   141 10590000  67300      794       6.8 2000.
## 6 Abilene  2000     6   156 13910000  66900      780       6.6 2000.
allCities <- txhousing %>%
  group_by(city) %>%
  plot_ly(x = ~date, y = ~median) %>%
  add_lines(alpha = 0.2, name = "Texan Cities", hoverinfo = "none")

allCities
allCities %>%
  filter(city == "Houston") %>%
  add_lines(name = "Houston")
#If we want to add more cities, need to use add_fun instead:
  allCities %>%
    add_fun(function(plot) {
      plot %>% 
        filter(city == "Houston") %>% 
        add_lines(name = "Houston")}) %>%
    add_fun(function(plot) {
      plot %>% filter(city == "Abilene") %>%
        add_lines(name= "Abilene")
  })
#Legends can be used to click on and remove/add traces very easily - make it easy to create images that you want to publish.


#Can also be used for 3D plots
  
#Plotting the iris dataset in 3D
plot_ly(data=iris, x=~Sepal.Length,y=~Sepal.Width,z=~Petal.Length,type="scatter3d",mode='markers',size=~Petal.Width,color=~Species)
## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.
#And animations! - useful if you have data across time for example.

df <- data.frame(
  x = c(1:5,4:1), 
  y = c(1:5, 4:1), 
  f = c(1:9)
)

p <- plot_ly(data=df, x = ~x, y = ~y, frame = ~f, type = 'scatter',transition= ~f, mode = 'markers', showlegend = TRUE)

  

p
## Warning: 'scatter' objects don't have these attributes: 'transition'
## Valid attributes include:
## 'type', 'visible', 'showlegend', 'legendgroup', 'opacity', 'name', 'uid', 'ids', 'customdata', 'selectedpoints', 'hoverinfo', 'hoverlabel', 'stream', 'transforms', 'x', 'x0', 'dx', 'y', 'y0', 'dy', 'text', 'hovertext', 'mode', 'hoveron', 'line', 'connectgaps', 'cliponaxis', 'fill', 'fillcolor', 'marker', 'selected', 'unselected', 'textposition', 'textfont', 'r', 't', 'error_x', 'error_y', 'xcalendar', 'ycalendar', 'xaxis', 'yaxis', 'idssrc', 'customdatasrc', 'hoverinfosrc', 'xsrc', 'ysrc', 'textsrc', 'hovertextsrc', 'textpositionsrc', 'rsrc', 'tsrc', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule', '_bbox'
p1 <- ggplot(df, aes(x, y)) +
    geom_point(aes(frame = f))
## Warning: Ignoring unknown aesthetics: frame
p1

ggplotly(p1)
# Link to the plotly getting started guide I used
#https://plotly-book.cpsievert.me/index.html 
#https://plot.ly/r/